package com.example.demo.Service;

import com.example.demo.entity.Comment;
import com.example.demo.entity.Like;
import com.example.demo.entity.Post;
import com.example.demo.entity.User;
import com.example.demo.repository.LikeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class LikeService {
    @Autowired
    private LikeRepository likeRepository;

    //为文章或评论点赞
    public Like save(Like like) {
        if (like.getPost() != null) {
            //检查是否已经对该文章点赞
            if (likeRepository.existsByPostAndUser(like.getPost(), like.getUser())) {
                throw new IllegalArgumentException("User has already liked this post");
            }
        } else if (like.getComment() != null) {
            //检查是否已经对该评论点赞
            if (likeRepository.existsByCommentAndUser(like.getComment(), like.getUser())) {
                throw new IllegalArgumentException("User has already liked this comment");
            }
        }
        //如果没有点赞过，保存新点赞
        return likeRepository.save(like);
    }

    //取消点赞
    public void deleteById(Long id) {
        likeRepository.deleteById(id);
    }

    //获取某篇文章的点赞数
    public Long countLikesByPost(Post post) {
        return likeRepository.countByPost(post);
    }

    //获取某条评论的点赞数
    public Long countLikesByComment(Comment comment) {
        return likeRepository.countByComment(comment);
    }

    //检查用户是否已经点赞某篇文章
    public Like hasLikedPost(Post post, User user) {
        if (likeRepository.existsByPostAndUser(post, user)) {
            throw new IllegalStateException("You have already liked this post.");
        }

        Like like = new Like();
        like.setPost(post);
        like.setUser(user);
        return likeRepository.save(like);
    }

    //检查用户是否已经点赞某条评论
    public Like hasLikedComment(Comment comment, User user) {
        if (likeRepository.existsByCommentAndUser(comment, user)) {
            throw new IllegalStateException("You have already liked this post.");
        }

        Like like = new Like();
        like.setComment(comment);
        like.setUser(user);
        return likeRepository.save(like);
    }

    //取消文章的点赞
    public void unlikePost(Post post, User user) {
        Like like = likeRepository.findByPostAndUser(post, user)
                .orElseThrow(() -> new IllegalStateException("Like not found."));
        likeRepository.delete(like);
    }

    //取消评论的点赞
    public void unlikeComment(Comment comment, User user) {
        Like like = likeRepository.findByCommentAndUser(comment, user)
                .orElseThrow(() -> new IllegalStateException("Like not found."));
        likeRepository.delete(like);
    }
}
